import json

import requests
import certifi

def product_list(_token:str):
    _url = 'https://www.bankwings.cn/th/api/getProductListFromApi.do'
    _data = {'token': _token, }
    _res = session.post(_url,headers=headers, json=_data, verify=certifi.where(), timeout=10)
    if _res.status_code == 200:
        result = _res.json()['data']
        return result
    return None



def product_detail(_token:str, _product_id:str):
    _url = 'https://www.bankwings.cn/th/api/getProductInfoFromApi.do'
    _data = {'token': _token, 'productId': _product_id}
    _res = session.post(_url, headers=headers, json=_data, verify=certifi.where(), timeout=10)
    if _res.status_code == 200:
        result = _res.json()['data']
        return result
    return None



def commission_list(_token:str):
    _url = 'https://www.bankwings.cn/th/api/commissionInfoList.do'
    _data = {'token': _token, 'commissionType':'0','yearAndMonth':'2025',}
    _res = session.post(_url,headers=headers, json=_data, verify=certifi.where(), timeout=10)
    if _res.status_code == 200:
        result = _res.json()['data']
        return result
    return None


def save_product(_product:dict):
    product_id = _product['productId']
    path = f'../web/uploads/{product_id}.json'
    json.dump(_product, open(path, 'w',encoding='utf-8'), indent=4, ensure_ascii=False)


if __name__ == "__main__":
    session = requests.Session()
    headers = {'Content-Type': 'application/json', }
    url = 'https://www.bankwings.cn/th/api/login/enter.do'
    data = {'inviteCode': '', 'phone': '13717616187', 'phoneCode': '111111'}
    res = session.post(url, headers=headers, json=data, verify=certifi.where(), timeout=10)
    if res.status_code == 200:
        token = res.json()["data"]["token"]
        headers['authorization'] = token
        print(f'{token=}')

        res_list = product_list(token)
        for product in res_list:
            res_product = product_detail(token, product["productId"])
            save_product(res_product)

        res_commission = commission_list(token)
        for commission in res_commission:
            print(commission)